//引入模块
const express = require("express");
//引入mysql连接池对象
const query = require("../util/query.js");
const { handleImgUrl } = require("../util/common.js");


//创建空路由器
let router = express.Router();
//挂载路由
// 1.6. 订单管理
//===============================================
// 1.6.1 创建订单 order/create
// 参数名	参数说明	备注
// address	收货地址对象{}
// amount 总金额
// note	备注信息
// goodsList	购买商品数组,如：
//	[{"id":"109","count":5,"price":129},
//   {"id":"111","count":23,"price":222}]  这里的id是指商品id
router.post("/create", async (req, res) => {
  //是否已登录
  let user = req.session.user;
  if (!user) {
    res.send({ code: 2, msg: "未登录" });
    return;
  }
  //以下代码没有考虑数据库的事务操作，需要进一步完善的....
  try {
    //1获取收货人地址编号数据
    let address = req.body.address;
    if (!address) throw "收货人地址不能为空";
    let note = req.body.note;
    let amount = req.body.amount || 0;
    if (!req.body.goodsList) throw "购买商品不能为空";
    

    let goodsList=[];
    
    req.body.goodsList.forEach(item=>goodsList.push(item));  //传递过来的订单商品列表
    console.log(goodsList);
    
    //处理获取收货地址
    // let sql = `select * from user_address where user_id = ${user.id} AND id = ${address_id}`;
    // let result = await query(sql);
    // if (result.length == 0) throw "收货地址不存在";
    // let address = result[0];

    // 判断库存是否全部充足，并计算总价格
    
    let orderGoods = []; //待新建的订单商品列表
    for (let i = 0; i < goodsList.length; i++) {
      //判断每个商品库存数量是否满足
      let item = goodsList[i];
      let sql = `select * from goods where id = ${item.id} AND num >= ${item.count} AND status = 1`;
      let result = await query(sql);

      if (result.length == 0) throw `部分商品库存不足`;

      //继续处理该商品      
      orderGoods.push({
        goods_id: item.id,
        count: item.count,
        price: item.price,
      });

      //修改商品的库存数量
      sql = `update goods set num = num - ${item.count} where id=${item.id}`;
      await query(sql);
    }    

    // 创建订单
    let order = {};
    order.user_id = user.id;
    order.address_name = address.name; 
    order.address_phone = address.phone;
    order.address_area = address.area;
    order.address_detail = address.detail;
    order.note = note;
    order.amount = amount;
    sql = "INSERT INTO user_order SET ?";
    result = await query(sql, [order]);
    let order_id = result.insertId;  //获取新订单的编号
    //插入订单项数据
    for(let i = 0; i < orderGoods.length ;i++){
      let goods = orderGoods[i];
      goods.order_id = order_id; //订单商品记录添加订单编号值
      sql = "INSERT INTO user_order_goods SET ?";
      await query(sql, [goods]);
    }
    res.send({ code: 1, msg: `创建订单成功`});
    
  } catch (error) {
    res.send({ code: -1, msg: `创建订单失败, 错误信息: ${error}` }); //throw err;
  }
});
//===============================================
// 1.6.1 创建订单 order/create
// 参数名	参数说明	备注
// address_id	收货地址id
// note	备注信息
// goods	购买商品信息数组,如：
//	[{"id":"109","count":5,"selected":true},
//   {"id":"111","count":23,"selected":true}]
router.post("/create_old", async (req, res) => {
  //是否已登录
  let user = req.session.user;
  if (!user) {
    res.send({ code: 2, msg: "未登录" });
    return;
  }
  //以下代码没有考虑数据库的事务操作，需要进一步完善的....
  try {
    //1获取收货人地址编号数据
    let address_id = parseInt(req.body.address_id);
    if (!address_id) throw "收货人地址不能为空";
    let note = req.body.note;

    if (!req.body.goods) throw "购买商品不能为空";

    let goodsList = JSON.parse(req.body.goods);  //传递过来的订单商品列表

    //处理获取收货地址
    let sql = `select * from user_address where user_id = ${user.id} AND id = ${address_id}`;
    let result = await query(sql);
    if (result.length == 0) throw "收货地址不存在";
    let address = result[0];

    // 判断库存是否全部充足，并计算总价格
    let amount = 0;
    let orderGoods = []; //待新建的订单商品列表
    for (let i = 0; i < goodsList.length; i++) {
      //判断每个商品库存数量是否满足
      let item = goodsList[i];
      let sql = `select * from goods where id = ${item.id} AND num >= ${item.count} AND status = 1`;
      let result = await query(sql);

      if (result.length == 0) throw `部分商品库存不足`;

      //继续处理该商品
      let goods = result[0];
      amount += goods.price * item.count;
      orderGoods.push({
        goods_id: item.id,
        count: item.count,
        price: goods.price,
      });

      //修改商品的库存数量
      sql = `update goods set num = num - ${item.count} where id=${item.id}`;
      await query(sql);
    }    

    // 创建订单
    let order = {};
    order.user_id = user.id;
    order.address_name = address.name; 
    order.address_phone = address.phone;
    order.address_area = address.area;
    order.address_detail = address.detail;
    order.note = note;
    order.amount = amount;
    sql = "INSERT INTO user_order SET ?";
    result = await query(sql, [order]);
    let order_id = result.insertId;  //获取新订单的编号
    //插入订单项数据
    for(let i = 0; i < orderGoods.length ;i++){
      let goods = orderGoods[i];
      goods.order_id = order_id; //订单商品记录添加订单编号值
      sql = "INSERT INTO user_order_goods SET ?";
      await query(sql, [goods]);
    }
    res.send({ code: 1, msg: `创建订单成功`});
    
  } catch (error) {
    res.send({ code: -1, msg: `创建订单失败, error: ${error}` }); //throw err;
  }
});

//===================================================
// 1.6.2 查询订单列表
// 参数名	参数说明	备注
// 无参数
router.get("/list", async (req, res) => {
  //是否已登录
  let user = req.session.user;
  if (!user) {
    res.send({ code: 2, msg: "未登录" });
    return;
  }

  try {
    //获取当前用户的订单
    let sql = `select * from v_user_order where user_id = ${user.id} `;
    let result = await query(sql);
    if (result.length == 0) throw "查询订单失败：当前用户没有订单！";
    let orders = result;

    // 获取每个订单的商品列表
    for(let i=0;i<orders.length;i++){
      let order = orders[i];
      let sql = `select  * from v_order_goods where order_id = ${order.id}`;
      let goodsList = await query(sql);      
      order.goods = goodsList; //添加该订单的商品
    }

    let data = orders;
    res.send({ code: 1, msg: `订单查询成功`, data });
  } catch (error) {
    res.send({ code: -1, msg: `订单查询失败, error: ${error}` }); //throw err;
  }
});

//===================================================
// 1.6.3 查询订单详情 order/detail
// 参数名	参数说明	备注
// id	订单id
router.get("/detail", async (req, res) => {
  //是否已登录
  let user = req.session.user;
  if (!user) {
    res.send({ code: 2, msg: "未登录" });
    return;
  }

  try {
    //请求参数
    let id = parseInt(req.query.id) || 0;
    if (!id) throw "查询的订单编号不能为空";

    //获取当前用户的订单
    let sql = `select * from user_order where user_id = ${user.id} AND id = ${id}`;
    let result = await query(sql);
    if (result.length != 1) throw "当前用户没有订单,或订单号重复了！";

    //当前用户有订单（只有1个)，则继续处理
    let order = result[0];
    // 获取订单的商品列表
    
    sql = `select  * from v_order_goods where order_id = ${order.id}`;
    let goodsList = await query(sql);    
    order.goods = goodsList; //添加该订单的商品   

    let data = order;
    res.send({ code: 1, msg: `订单查询成功`, data });
  } catch (error) {
    res.send({ code: -1, msg: `订单查询失败, error: ${error}` }); //throw err;
  }
});

//===================================================
// 1.6.4 取消订单  order/cancel
// 参数名	参数说明	备注
// id	订单id
router.post("/cancel", async (req, res) => {
  //是否已登录
  let user = req.session.user;
  if (!user) {
    res.send({ code: 2, msg: "未登录" });
    return;
  }

  try {
    //请求参数
    let id = parseInt(req.body.id) || 0; //POST从body中取参数
    if (!id) throw "取消的订单编号不能为空";

    //获取当前用户的订单  (包括已取消的)
    let sql = `select * from user_order where user_id = ${user.id} AND id = ${id}`;
    let result = await query(sql);
    if (result.length != 1)
      throw "当前用户没有订单或有重复的订单号记录！";

    //当前用户有一条订单，则继续处理
    let order = result[0];
    //获取该订单的商品列表

    sql = `select  * from v_order_goods where order_id = ${order.id}`;
    let goodsList = await query(sql);

    //订单商品数量要回加到对应商业的库存数
    for(let i=0;i<goodsList.length;i++){
      let item = goodsList[i];
      sql = `update goods set num = num + ${item.count} where id=${item.goods_id}`;
      await query(sql);
    }
    
    //设置订单的取消标志值
    sql = `update user_order set is_cancel = 1 where id=${order.id}`;
    await query(sql);
    res.send({ code: 1, msg: `订单取消成功`});
  } catch (error) {
    res.send({ code: -1, msg: `订单取消失败, error: ${error}` }); //throw err;
  }
});

//===============================================
//导出路由器
module.exports = router;